<template>
  <div>
    <el-tree
      ref="treeRef"
      :data="treeList"
      show-checkbox
      :props="listProps"
      default-expand-all
      node-key="id"
      :default-checked-keys="checkedList"
    />
    <div class="flex">
      <el-button @click="empty">清空</el-button>
      <el-button type="primary" @click="determine">确定</el-button>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref } from "vue";
import { useRoute, useRouter } from "vue-router";
import { treeListApi, roleListByIdAPI, roleAllocMenuAPI } from "./api";
import { ElMessage, ElTree } from "element-plus";

const treeRef = ref<InstanceType<typeof ElTree>>();

const route = useRoute();
const router = useRouter();

//分配菜单响应数据
const treeList = ref<ITreeList[]>([]);
//默认勾选的数组
const checkedList = ref<number[] | any>([]);

//决定树形的展示内容
const listProps = {
  children: "children",
  label: "title",
  id: "id",
};

//分配菜单请求
treeListApi().then((res) => {
  if (res.code === 200) {
    treeList.value = res.data;
  }
});
//根据id请求
if (route.query.id) {
  roleListByIdAPI(parseInt(route.query.id as string)).then((res) => {
    if (res.code === 200) {
      checkedList.value = res.data.map((item) => {
        if (item.parentId !== 0) {
          return item.id;
        }
      });
    }
  });
}

//清空
const empty = () => {
  treeRef.value?.setCheckedNodes([], false);
  checkedList.value = [];
};
//确定
const determine = () => {
  //获取当前选中的数组
  checkedList.value = treeRef.value?.getCheckedKeys() as number[];
  if (route.query.id) {
    roleAllocMenuAPI(
      parseInt(route.query.id as string),
      checkedList.value
    ).then((res) => {
      if (res.code === 200) {
        //提示
        ElMessage.success("分配菜单成功");
        //跳转到角色列表
        router.push("/ums/role");
      }
    });
  }
};
</script>

<style scoped>
.flex {
  text-align: center;
  padding: 20px;
}
</style>
